"use strict";

const BaseController = require("./base");
const SysUserDto = require("../dto/sys-user.dto");

class AuthController extends BaseController {

  //生成token
  async getToken() {
    try {
      //通过dto.js约束参数,然后返回有约束的参数
      const verifytRes = this.verifytParams(SysUserDto.loginDto);
      if (!verifytRes.success) throw verifytRes.msg;

      //#region  获取数据
      const checkUser = await this.service.system.sysUser.checkUserCanLogin(verifytRes.params)
      if (!checkUser.success) throw checkUser.msg;
      //#endregion

      //#region 进一步校验登录
      const userEntity = this.ctx.helper.deepCopy(checkUser.data);
      if (userEntity.password !== verifytRes.params.password) throw '登录密码错误';
      if (!userEntity.status) throw '当前账号已被禁用，无法登录'

      // TODO 判断是否需要邮箱验证，如果账号最后的登录ip为空或不跟当前的登录ip一致，则需要邮箱验证码
      let check = false;


      // 设置token
      delete userEntity.company
      // 根据秘钥和id值创建redisKey
      const redisKey = `${this.config.companyConfig.redisKey}${userEntity.id}`;
      const token = await this.ctx.helper.createToken({ ...userEntity, redisKey })
      // 将{ ...userEntity, redisKey }存储在redis中,后期可以通过token拿到对应的redisKey
      await this.ctx.helper.setRedis(redisKey, { ...userEntity, redisKey }, 24 * 60 * 60)

      // 更新最后登录IP跟登录时间
      const loginIp = this.ctx.request.ip.replace(/::ffff:/, "");
      const loginTime = new Date();
      await this.service.system.sysUser.edit(userEntity.id, {
        loginIp,
        loginTime
      })

      await this.success({ token, check });
    } catch (err) {
      console.log(err)
      await this.error(err);
    }
  }


  //通过token获取到对应的信息
  async getUserInfo() {
    try {
      const res = await this.getLoginUser();
      //这里查询用户、角色、菜单表
      const userRes = await this.service.system.sysUser.getUserInfo(res.id);
      if (!userRes.success) throw userRes.msg;

      let userEntity = this.ctx.helper.deepCopy(userRes.data);
      let roles = [], menus = [], permissions = [];

      roles = userEntity.role;
      delete userEntity.role;

      // 检查是否存在有效角色
      let vaildRole = roles.filter(role => role.status);
      if (!vaildRole.length) throw '账号未绑定角色或所属角色已被禁用'
      // 被禁用的角色不展示对应菜单,以下进行解析出菜单
      vaildRole.map(role => {
        // console.log(role)
        delete role.sys_user_role;
        menus = menus.concat(role.menu);
        delete role.menu;
      })
      // 多角色用户可能出现菜单重复，需要去重
      menus = this.ctx.helper.uniqueArrayByObj(this.ctx.helper.deepCopy(menus), 'id')
      menus.map(menu => {
        permissions.push(menu.perm);
        delete menu.role_menu
      });
      // console.log(menus)
      if (menus.length === 0) throw '角色未分配菜单，无法登录'
      let _menus = menus.filter(menu => menu.type !== 2);
      _menus.map(menu => {
        menu.meta = {
          title: menu.title
        }
        delete menu.sys_role_menu
      })
      // console.log(_menus)
      _menus = this.ctx.helper.translateDataToTree(_menus, 0);
      // console.log(_menus)
      //根据每个菜单权限的sort进行排序从小到大进行排序
      _menus.map(menu => {
        menu.children = menu.children.sort((a, b) => a.sort - b.sort);
      })
      await this.success({
        user: userEntity,
        roles,
        menus: _menus,
        permissions,
      })
    } catch (err) {
      await this.error(err);
    }
  }
}

module.exports = AuthController;
